package com.chl.tools;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.w3c.dom.Document;

public class DocStyleXmlCheck {
	
	private static final Logger log = Logger.getLogger(DocStyleXmlCheck.class.getName());

	public static void main(String[] args) {
		
		String urls = "";
		
		
		String[] ul = urls.split("@@@");
		
		int total = ul.length;
		ArrayList<String> al = new ArrayList<String>();
		
		for(int i = 0; i < total ; i++) {
			checkUrl(al,ul[i]);
			
			log.log(Level.INFO,  i + "/" + total);
		}
		
		System.out.println(al.toString());
		
	}

	
	/**
	 * 检测文档地址
	 * @param urlPath
	 */
	private static void checkUrl( ArrayList<String> al ,String urlPath) {
		try (InputStream fis = new BufferedInputStream(new URL(urlPath).openStream())) {

			OPCPackage opcPackage = OPCPackage.open(fis);
			PackagePart part = opcPackage.getParts().stream()
					.filter(item -> item.getPartName().getName().equals("/word/styles.xml")).findFirst()
					.orElse(null);

			InputStream wordRelsInputStream = part.getInputStream();

			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(wordRelsInputStream);

			String content = convertDocumentToString(doc);
			
			if(content.indexOf("<w:spacing w:before=\"260\" w:after=\"260\"") > 0 ) {
				al.add(urlPath);
			}

		} catch (Exception e) {
			System.out.println(e);
		}
		
	}
	
	
	/**
	 * 将 Document 转换为 XML 字符串
	 * 
	 * @param doc
	 * @return
	 * @throws TransformerException
	 */
	public static String convertDocumentToString(Document doc) throws TransformerException {
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();

		// 设置输出格式（缩进、编码等）
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

		DOMSource source = new DOMSource(doc);
		StringWriter writer = new StringWriter();
		StreamResult result = new StreamResult(writer);

		transformer.transform(source, result);

		return writer.toString();
	}

}
